/*
 * Copyright (C) 2008 TranceCode Software
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 *
 * $Id$
 */
package org.trancecode.rdf.query;

import org.trancecode.core.function.TubularPredicates;
import org.trancecode.rdf.IterableModel;
import org.trancecode.rdf.Model;
import org.trancecode.rdf.Triple;
import org.trancecode.rdf.TripleFunctions;

import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;


/**
 * @author Herve Quiroz
 * @version $Revision: 3842 $
 */
public class GenericExecutableTripleQuery implements ExecutableTripleQuery
{
	private final Model result;


	protected GenericExecutableTripleQuery(final Model model, final TripleQuery tripleQuery)
	{
		super();
		Preconditions.checkNotNull(model);

		if (tripleQuery.subjects.isEmpty() && tripleQuery.predicates.isEmpty() && tripleQuery.objects.isEmpty()
			&& tripleQuery.references.isEmpty())
		{
			result = model;
		}
		else
		{
			final List<Predicate<Triple>> triplePredicates = Lists.newArrayListWithExpectedSize(3);

			if (!tripleQuery.subjects.isEmpty())
			{
				triplePredicates.add(Predicates.compose(
					TubularPredicates.isContainedBy(tripleQuery.subjects), TripleFunctions.subject()));
			}

			if (!tripleQuery.objects.isEmpty())
			{
				triplePredicates.add(Predicates.compose(
					TubularPredicates.isContainedBy(tripleQuery.objects), TripleFunctions.object()));
			}

			if (!tripleQuery.predicates.isEmpty())
			{
				triplePredicates.add(Predicates.compose(
					TubularPredicates.isContainedBy(tripleQuery.predicates), TripleFunctions.predicate()));
			}

			if (!tripleQuery.references.isEmpty())
			{
				triplePredicates.add(Predicates.compose(
					TubularPredicates.isContainedBy(tripleQuery.references), TripleFunctions.reference()));
			}

			final Predicate<Triple> filter = Predicates.and(triplePredicates);
			result = IterableModel.of(Iterables.filter(model.triples(), filter));
		}
	}


	@Override
	public Model execute()
	{
		return result;
	}
}
